package com.zlp.partice.jvm;

import java.lang.invoke.*;

import static java.lang.invoke.MethodHandles.lookup;

/**
 * @author: zhulaiping
 * @create: 2021-12-08 12:33
 * todo:
 *
 **/
public class InvokeDynamic {
    public static void main(String[] args) throws Throwable {
        INDY_BootstrapMethod().invokeExact("icyfenix");
    }
    private static MethodHandle INDY_BootstrapMethod() throws Throwable {
        CallSite cs = (CallSite) MH_BootstrapMethod()
                .invokeWithArguments(lookup(), "testMethod",
                        MethodType.fromMethodDescriptorString("(Ljava/lang/String;)V", null));
        return cs.dynamicInvoker();
    }
    private static MethodHandle MH_BootstrapMethod() throws Throwable {
        return lookup().findStatic(InvokeDynamic.class, "BootstrapMethod", MT_BootstrapMethod());
    }
    private static MethodType MT_BootstrapMethod() {
        MethodType methodType = MethodType
                .fromMethodDescriptorString("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String; Ljava/lang/invoke/MethodType"
                        ,InvokeDynamic.class.getClassLoader());
        return methodType;
    }
    public static void testMethod(String s) {
        System.out.println("hello String:" + s);
    }

    
    public static CallSite BootstrapMethod(MethodHandles.Lookup lookup,
                                           String name, MethodType mt) throws NoSuchMethodException, IllegalAccessException {
        return new ConstantCallSite(lookup.findStatic(InvokeDynamic.class, name, mt));
    }






}
